package com.one.blocks.rbac.security;

import com.one.blocks.rbac.domain.SysUser;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;

/**
 * @author <a href="mailto:idler41@163.con">linfuxin</a> created on 2023-08-12 20:11:51
 */
@Data
public class RbacUserDetails implements UserDetails {

    /**
     * 主键ID
     */
    private Integer userId;

    /**
     * 用户详情，登录认证时有数据，认证成功后每次访问都为null，因为不是每次请求都需要用户所有信息
     * 如果需要用户详情，可根据userId手动加载
     */
    private transient SysUser sysUser;

    /**
     * 登录时间
     */
    private LocalDateTime loginTime;

    /**
     * 登录过期时间
     */
    private LocalDateTime loginExpireTime;

    /**
     * 变更密码过期时间
     */
    private LocalDateTime changeExpireTime;

    /**
     * 访问时间
     */
    private transient LocalDateTime accessTime;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 角色与权限在鉴权时动态加载
        return Collections.emptyList();
    }

    @Override
    public boolean isAccountNonExpired() {
        return loginExpireTime.isAfter(accessTime);
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.sysUser.getState() == 1;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return changeExpireTime.isAfter(accessTime);
    }

    @Override
    public boolean isEnabled() {
        return this.sysUser != null && this.sysUser.getState() == 1;
    }

    @Override
    public String getPassword() {
        return this.sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        return this.sysUser.getUsername();
    }
}
